# Copyright 2010 Mikko Rantanen
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import fuse
import logging
import sys

entrytypes = {}

def registertype(type, typeid, typekey, *types):
    """
    Registers classes for each folder content item type

    The registrations are done in the model/__init__
    """

    assert not entrytypes.get(typeid), 'Multiple types with same type id'
    if __debug__:
        if len(types) == 0:
            types = [ type ]

        for t in types:
            assert getattr(t, 'get_urlname'), 'The type must implement get_urlname'
            assert getattr(t, 'get_name'), 'The type must implement get_name'

    entrytypes[typeid] = { 'ctor': type, 'key': typekey }

def constructtype(parent, iteminfo):
    try:
        typeid = iteminfo['FolderContentItemType']
        entrytype = entrytypes[typeid]

        ctor = entrytype['ctor']
        data = iteminfo[entrytype['key']]
        return ctor(parent, data)
    except:
        logging.error(':<')
        logging.error(sys.exc_info())


class FSEntry(fuse.Stat):
    """
        Base type for all MFilesFS file system items.
    """

    def __init__(self, parent, iteminfo):
        """
        Initializes the base data.
        
        parent: Parent FSEntry. None for vault root.
        iteminfo: M-Files folder content item. None for vault root.
        """

        self.parent = parent
        self.iteminfo = iteminfo
    
    def get_conn(self):
        # CACHEABLE: Recursion, might be used often.
        return self.parent.get_conn()

    def get_urlpath(self):
        # CACHEABLE: Might result in lots of recursion
        return self.parent.get_urlpath() + '/' + self.get_urlname()

    def get_fspath(self):
        # CACHEABLE: Might result in lots of recursion
        parentpath = self.parent.get_fspath()
        if parentpath == '/':
            parentpath = ''
        return parentpath + '/' + self.get_name()



